const storageService = require('../../services/storage');
import * as comm from '../../utils/common';
// 获取 App 实例
const appInstance = getApp();
Page({
  data: {
    progressStyle: 'width: 0%',
    loadingText: '正在初始化...',
    fadeOutAnimation: {},
    loadingTextAnimation: {},
    lastTextIndex: -1,
  },

  onLoad: function () {
    let dids = storageService.getDeviceIds()
    const devices = storageService.batchGetDeviceInfo(dids)
    const topicSubArr = [];
    devices.forEach(device => {
      topicSubArr.push({
        topicSend: device.topicSend,
        topicSub: device.topicSub
      })
      this.handleDeviceType(device)
    })

    appInstance.initDeviceStatusMap();
   // appInstance.mtSubscribe(topicSubArr);
    if (dids.length > 0 && appInstance.globalData.isRelease) {
      comm.httpGet("/device/active?ids=" + dids.join(":"))
    }

    this.simulateLoading()
    this.preloadNextPage()
  },

  onReady: function () {
    // 页面渲染完成后，所有动画通过WXML和WXSS自动开始
  },
  handleDeviceType: function (device) {
    if (device.deviceVer.startsWith("H")) {
      return
    } else if (device.deviceVer.startsWith("D")) {
      if (device.deviceVer.endsWith("_1")) {
        if ("freshwater_lamp" != device.deviceType) {
          device.deviceType = "freshwater_lamp"
          storageService.saveDeviceInfo(device.deviceId, device)
        }
      } else if ("seawater_diy_lamp" != device.deviceType) {
        device.deviceType = "seawater_diy_lamp"
        storageService.saveDeviceInfo(device.deviceId, device)
      }
    } else {
      if (!device.deviceType || "orig_diy_lamp" != device.deviceType) {
        device.deviceType = "orig_diy_lamp"
        storageService.saveDeviceInfo(device.deviceId, device)
      }
    }
  },

  simulateLoading: function () {
    const totalDuration = 3500 // 配合更舒缓的动画节奏
    const updateInterval = 16
    const startTime = Date.now()

    const loadingTexts = ['', '构建光影...', '描绘意境...', '即将呈现...']

    const timer = setInterval(() => {
      const elapsed = Date.now() - startTime
      let progress = Math.min(100, (elapsed / totalDuration) * 100)
      progress = this.easeInOutQuad(progress / 100) * 100

      let textIndex = Math.floor(progress / (100 / loadingTexts.length))
      textIndex = Math.min(textIndex, loadingTexts.length - 1)

      const updateData = {
        progressStyle: `width: ${progress}%`,
      }

      if (this.data.lastTextIndex !== textIndex) {
        // 创建一个新的动画实例来实现文本的淡入淡出
        const textAnimation = wx.createAnimation({
          duration: 300,
          timingFunction: 'ease-in-out'
        })
        textAnimation.opacity(0).step()
        updateData.loadingTextAnimation = textAnimation.export()

        setTimeout(() => {
          const fadeInAnimation = wx.createAnimation({
            duration: 300,
            timingFunction: 'ease-in-out',
          })
          fadeInAnimation.opacity(1).step()
          this.setData({
            loadingText: loadingTexts[textIndex],
            loadingTextAnimation: fadeInAnimation.export(),
            lastTextIndex: textIndex,
          })
        }, 300)
      }

      this.setData(updateData)

      if (progress >= 100) {
        clearInterval(timer)
        setTimeout(() => {
          this.fadeOutAndNavigate()
        }, 500) // 加载完成后稍作停留
      }
    }, updateInterval)
  },

  // 缓动函数，保持不变
  easeInOutQuad: function (t) {
    return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
  },

  fadeOutAndNavigate: function () {
    const animation = wx.createAnimation({
      duration: 1000, // 增加淡出时间
      timingFunction: 'ease-out',
    })

    animation.opacity(0).step()

    this.setData({
      fadeOutAnimation: animation.export(),
    })

    setTimeout(() => {
      this.navigateToHome()
    }, 1000) // 与动画时长匹配
  },

  preloadNextPage: function () {
    try {
      const systemInfo = {
        ...wx.getDeviceInfo(),
        ...wx.getWindowInfo(),
        ...wx.getAppBaseInfo(),
      }
      getApp().globalData.systemInfo = systemInfo

      // 可以根据需要添加更多预加载项
    } catch (error) {
      console.error('预加载资源失败:', error)
    }
  },

  navigateToHome: function () {
    wx.redirectTo({
      url: '/pages/index/index',
      fail: err => {
        console.error('redirectTo 失败，尝试 switchTab:', err)
        wx.switchTab({
          url: '/pages/index/index',
          fail: switchErr => {
            console.error('switchTab 也失败:', switchErr)
          },
        })
      },
    })
  },
})